/**
 * 
 */
package com.open.openfinalshell;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import com.jediterm.pty.PtyProcessTtyConnector;
import com.jediterm.terminal.TtyConnector;
import com.jediterm.terminal.ui.JediTermWidget;
import com.jediterm.terminal.ui.UIUtil;
import com.jediterm.terminal.ui.settings.DefaultSettingsProvider;
import com.pty4j.PtyProcess;
import com.pty4j.PtyProcessBuilder;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author david
 *
 */
public class MainWindow {
	
	private JFrame win;
	private JTabbedPane tabp;
	
	private static @NotNull JediTermWidget createTerminalWidget() {
	    JediTermWidget widget = new JediTermWidget(80, 24, new DefaultSettingsProvider());
	    widget.setTtyConnector(createTtyConnector());
	    widget.start();
	    return widget;
	  }

	  private static @NotNull TtyConnector createTtyConnector() {
	    try {
	      Map<String, String> envs = System.getenv();
	      String[] command;
	      if (UIUtil.isWindows) {
	        command = new String[]{"cmd.exe"};
	      } else {
	        command = new String[]{"/bin/bash", "--login"};
	        envs = new HashMap<>(System.getenv());
	        envs.put("TERM", "xterm-256color");
	      }

	      PtyProcess process = new PtyProcessBuilder().setCommand(command).setEnvironment(envs).start();
	      return new PtyProcessTtyConnector(process, StandardCharsets.UTF_8);
	    } catch (Exception e) {
	      throw new IllegalStateException(e);
	    }
	  }
	
	public MainWindow() {
		win = new JFrame();
		win.setTitle("TestTerminal");
		win.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		win.setSize(800, 500);
		win.setLocationRelativeTo(null);
		
		tabp = new JTabbedPane();
		tabp.addTab("tab1", createTerminalWidget());
		
		win.add(tabp);
		win.setContentPane(tabp);
	}
	
	public void show() {
		win.setVisible(true);
	}

}
